//
//  DLUserManager.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/22.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLUserManager.h"
#import "DLUserInfoModel.h"


#define LocalDataPath [NSString stringWithFormat:@"%@/Documents/LocalUserData.txt",NSHomeDirectory()]
#define LocalTokenPath [NSString stringWithFormat:@"%@/Documents/LocalTokenData.txt",NSHomeDirectory()]


@implementation DLUserManager

static DLUserManager *_userInfo = nil;
+ (instancetype)currentUser {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _userInfo = [[self alloc] init];
    });
    return _userInfo;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        NSDictionary *dic = [self getDataWithPath:LocalDataPath];
        if (dic.allKeys.count>1) {
            [self analyzeUserDataWithDict:dic];
        }else{
            [self initEmptyData];
        }
    }
    return self;
}
- (void) initEmptyData {
    
    [self saveDataWithDict:[[NSDictionary alloc] init] withPath:LocalDataPath];
    [self saveDataWithDict:[[NSDictionary alloc] init] withPath:LocalTokenPath];
    self.isLogin = NO;
    self.userInfoModel.userid = @"";
    self.userInfoModel.token = @"";
}

- (void)saveLoginTokenDict:(NSDictionary *)dict {
    if (isEmpty(dict)) {
        return;
    }
    [self saveDataWithDict:dict withPath:LocalTokenPath];
}
//保存数据
-(void)saveDataWithDict:(NSDictionary *)dict withPath:(NSString *)path {
    
    NSData *resultData= [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSFileManager *fm=[NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
        [fm createFileAtPath:path contents:nil attributes:nil];
    }
    [resultData writeToFile:path atomically:YES];
}

//得到数据
-(NSDictionary *)getDataWithPath:(NSString *)path{
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSDictionary *dict;
    if (data) {
        dict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:path] options:NSJSONReadingMutableContainers error:nil];
    }else{
        dict = [[NSDictionary alloc] init];
    }
    return dict;
}


#pragma mark  - 数据解析
-(void)analyzeUserDataWithDict:(NSDictionary *)dict{
    if (isEmpty(dict)) {
        return;
    }
    
    NSDictionary *tokenDict = [self getDataWithPath:LocalTokenPath];
    
    NSMutableDictionary *userData = [[NSMutableDictionary alloc] initWithDictionary:dict];
    
    if (isEmpty(dict)) {
        
    } else {
        [userData setObject:kSafeString(tokenDict[@"token"]) forKey:@"Token"];
//        kuserManager.isTokenAvailable = YES;//崩溃
        self.isTokenAvailable = YES;
    }
    
    self.userInfoModel = [DLUserInfoModel mj_objectWithKeyValues:userData];
    
    if (isEmpty(self.userInfoModel.userid)) {
        
        self.userInfoModel.token = userData[@"token"];
    }
    
    [self saveDataWithDict:userData withPath:LocalDataPath];
    
    if (self.userInfoModel.userid) {
        self.isLogin = YES;
    }else {
        self.isLogin = NO;
    }
}

#pragma mark  -登录
- (void) userLogin {
    
    DLLoginVC *vc = [DLLoginVC new];
    DLBaseNavController *loginNav = [[DLBaseNavController alloc] initWithRootViewController:vc];
    [self.lastVc.tabBarController presentViewController:loginNav animated:YES completion:^{
        
    }];
}


#pragma mark  -退出登录
- (void) userLogout {
    
    //弹出提示框
    UIAlertController *logoutAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定退出登录吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self logoutAction];
    }];
                           
    [logoutAlert addAction:cancel];
    [logoutAlert addAction:sure];
    [self.lastVc presentViewController:logoutAlert animated:YES completion:^{
    }];
}
- (void) logoutAction {
    
    NSString *postUrl = HTTPLogout;
    NSDictionary *postDic = @{
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        
        if (kRequestSuccess(responseObject) || ([[responseObject objectForKey:@"code"] intValue]==501)) {
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            
            [self initEmptyData];
            self.isRequestUserInfo = NO;
            [self.lastVc.navigationController popToRootViewControllerAnimated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.lastVc.tabBarController.selectedIndex = 0;
                self.isRequestUserInfo = YES;
            });
        } else {
            
//            kuserManager.isLogin = NO;
//            kuserManager.isTokenAvailable = NO;
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                self.lastVc.tabBarController.selectedIndex = 0;
//                [self userLogin];
//            });
        }
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
    }];
}

@end
